class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        h = ListNode(-1)
        h.next = head
        p_pre = h
        pp = head
        while True:
            tt = pp
            t = pp
            i = 1
            while i < k and t:
                t = t.next
                i += 1
            if not t:
                break
            pre = p_pre
            p = pre.next
            while pre != t:
                ne = p.next
                p.next = pre
                pre = p
                p = ne
            p_pre.next = t
            pp.next = p
            pp = p
            p_pre = tt
        return h.next


a = [1,2,3,4,5,6,7,8,9]
h = ListNode(0)
p = h
for i in range(len(a)):
    p.next = ListNode(a[i])
    p = p.next

h = Solution().reverseKGroup(h, 2)
while h:
    print(h.val)
    h = h.next
